﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Data.EntityClient;

using HelpCentral.Configuration;
using HelpCentral.Shared.Interfaces;
using HelpCentral.Data.Model;

namespace HelpCentral.Data.Repository
{
    public class ClientRepository : IClientRepository
    {
        HelpCentralModelContainer context = ContextContainer.Instance;

        #region IClientRepository Members

        public IClient FetchClientById(int clientId)
        {
            var c = context.Clients.FirstOrDefault(x=>x.ClientId == clientId);

            return (c == null) ? null : c.FromRepositoryObject();
        }

        public IClient FetchClientByLicense(Guid license)
        {
            var c = context.Clients.FirstOrDefault(x => x.License == license);

            return (c == null) ? null : c.FromRepositoryObject();
        }

        public IEnumerable<IClient> FetchAllClients()
        {
            return context.Clients.AsEnumerable().Select(x => x.FromRepositoryObject());
        }

        public IEnumerable<IClient> FetchActiveClients()
        {
            return context.Clients.Where(x => x.ActivateDate <= DateTime.UtcNow && (x.DeactivateDate == null || x.DeactivateDate >= DateTime.UtcNow)).AsEnumerable().Select(x => x.FromRepositoryObject());
        }

        public IClient CommitClient(IClient client)
        {
            var c = client.ToRepositoryObject(context);

            if (c.EntityState == System.Data.EntityState.Detached)
            {
                context.AddToClients(c);
            }

            context.SaveChanges();

            return c.FromRepositoryObject();
        }

        #endregion
    }
}
